
from langchain_core.tools import tool as create_tool
from langchain_core.runnables import RunnableConfig
from langgraph.types import interrupt
from langgraph.prebuilt.interrupt import HumanInterruptConfig
from typing import Callable
from langchain_core.tools import BaseTool


def tool_check(
        tool: Callable | BaseTool,
        *,
        interrupt_config: HumanInterruptConfig = None
) -> BaseTool:
    """为工具添加人工审核的包装器函数"""
    if not isinstance(tool, BaseTool):
        tool = create_tool(tool)
    if interrupt_config is None:
        # 设置默认审核配置，允许接受、修改、响应
        interrupt_config = {
            "allow_accept": True,
            "allow_edit": True,
            "allow_respond": True
        }

    @create_tool(
        tool.name,
        description=tool.description,
        args_schema=tool.args_schema
    )
    def call_tool_with_interrupt(config: RunnableConfig, **tool_input):
        # 生成审核请求，包含工具名称和参数
        request = {
            "action_request": {
                "action": tool.name,
                "args": tool_input
            },
            "config": interrupt_config,
            "description": "请审核工具调用"
        }
        # 触发中断，等待人工审核响应
        response = interrupt([request])[0]

        if response["type"] == "accept":
            # 审核通过，执行原始工具
            return tool.invoke(tool_input, config)
        elif response["type"] == "edit":
            # 审核修改，使用新参数
            tool_input = response["args"]["args"]
            return tool.invoke(tool_input, config)
        elif response["type"] == "response":
            # 直接返回用户反馈，不执行工具
            return response["args"]
        else:
            raise ValueError(f"不支持的审核响应: {response['type']}")

    return call_tool_with_interrupt